package netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.dns.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.NetUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DnsUdpClient {

    // google 8.8.8.8
    // 114.114.114.114 114.114.115.115
    // ali: 223.5.5.5 223.6.6.6
    // baidu: 180.76.76.76
    // 电信：首选：101.226.4.6
    // 联通：首选：123.125.81.6
    // 移动：首选：101.226.4.6
    // 铁通：首选：101.226.4.6

    static final String DNS_SERVER_HOST = System.getProperty("host", "101.226.4.6");
    static final int DNS_SERVER_PORT = Integer.parseInt(System.getProperty("port", "53"));

    static final String QUERY_DOMAIN = "www.example.com";

    public static void main(String[] args) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .handler(new ChannelInitializer<DatagramChannel>() {
                        @Override
                        protected void initChannel(DatagramChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new LoggingHandler(LogLevel.INFO));

                            p.addLast(new DatagramDnsQueryEncoder());
                            p.addLast(new DatagramDnsResponseDecoder());
                            p.addLast(new SimpleChannelInboundHandler<DatagramDnsResponse>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, DatagramDnsResponse msg) {
                                    try {
                                        handleQueryResp(msg);
                                    } finally {
                                        ctx.close();
                                    }
                                }
                            });
                        }
                    });

            // Make the connection attempt.
            ChannelFuture f = b.bind(0).sync();
            Channel ch = f.channel();

            InetSocketAddress addr = new InetSocketAddress(DNS_SERVER_HOST, DNS_SERVER_PORT);

            int randomID = new Random().nextInt(60000 - 1000) + 1000;
            DnsQuery query = new DatagramDnsQuery(null, addr, 1)
                    .setRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.A));
            // query.addRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.NS));
            // query.addRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.CNAME));
            ch.writeAndFlush(query).sync();
            boolean success = ch.closeFuture().await(10, TimeUnit.SECONDS);
            if (!success) {
                log.info("dns query timeout!");
                ch.close().sync();
            }

            // Wait until the connection is closed.
            // ch.closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    private static void handleQueryResp(DefaultDnsResponse msg) {
        log.info(">>> count: {}", msg.count());
        log.info(">>> count: {}", msg);
        if (msg.count(DnsSection.QUESTION) > 0) {
            DnsQuestion question = msg.recordAt(DnsSection.QUESTION, 0);
            log.info(">>> name: {}", question.name());
        }
        for (int i = 0, count = msg.count(DnsSection.ANSWER); i < count; i++) {
            DnsRecord record = msg.recordAt(DnsSection.ANSWER, i);
            if (record.type() == DnsRecordType.A) {
                //just print the IP after query
                DnsRawRecord raw = (DnsRawRecord) record;
                log.info(">>> raw-dns: {}", NetUtil.bytesToIpAddress(ByteBufUtil.getBytes(raw.content())));
            }
        }
    }
}
